package com.example.musicplayer;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.settings.MusicData;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.settings.SettingsItem;
import com.example.musicplayer.user.User;
import com.example.musicplayer.user.UserManage;

import java.util.ArrayList;
import java.util.List;

//简单数据配置的存储
public class DataLoadManager {
    //more features settings
    public static final String TIME_TO_EXIT_ON = "timeToExitOn";
    public static final String TIMING_SET = "timingSet";
    public static final String TIMED_OFF_IMMEDIATE = "timedOffImmediate";

    public static final String AUTO_INTO_PLAY_SCREEN = "autoIntoPlayScreen";
    public static final String ALLOW_PLAY_WITH_OTHER = "allowPlayWithOther";
    public static final String USE_NOTIFICATION_BAR = "useNotificationBar";
    public static final String DESKTOP_LYRIC = "desktopLyric";
    public static final String DESKTOP_LYRIC_LOCK = "desktopLyricLock";
    public static final String DESKTOP_LYRIC_IN_APP = "desktopLyricInApp";
    public static final String ANIM_EFFECT = "animEffect";
    public static final String PLAY_SCREEN_BACKGROUND = "playScreenBackground";
    public static final String MUSIC_PLAY_LIST_BACKGROUND = "playListBackground";
    public static final String DISPLAY_VISUALIZER = "displayVisualizer";
    public static final String ENABLE_BASS_BOOST = "enableBassBoost";
    public static final String BASS_BOOST_STRENGTH = "bassBoostStrength";
    public static final String ENABLE_VIRTUAL = "enableVirtual";
    public static final String VIRTUAL_STRENGTH = "virtualStrength";
    public static final String ENABLE_REVERB = "enableReverb";
    public static final String REVERB_LEVEL = "reverbLevel";
    public static final String ADD_TO_PLAY_LIST_TAIL = "addToPlayListTail";

    public static final String LYRIC_TEXT_SIZE = "lyricTextSize";
    public static final String DESKTOP_LYRIC_VIEW_LOC_Y = "desktopLyricViewLocY";
    public static final String DESKTOP_LYRIC_SIZE = "desktopLyricSize";
    public static final String DESKTOP_LYRIC_COLOR = "desktopLyricColor";
    public static final String DESKTOP_LYRIC_BACKGROUND = "desktopLyricBackground";
    public static final String PLAY_SCREEN_IMAGE = "playScreenImage";
    public static final String MUSIC_PLAY_LIST_IMAGE = "musicPlayListImage";
    //歌曲播放状态的信息标签
    private static final String MUSIC_LIST_TYPE = "musicListType";
    private static final String MUSIC_PLAY_MODE = "musicPlayMode";
    private static final String MUSIC_MENU_NAME = "musicMenuName";
    private static final String CURRENT_MUSIC_ID = "currentMusicId";
    private static final String CURRENT_MUSIC_TIME = "currentMusicTime";
    private static final String CURRENT_MUSIC_COUNTS = "currentMusicCounts";
    private static final String CURRENT_MUSIC_LIST = "currentMusicList_";
    //save the user state
    private static final String USER_LOGIN = "userLogin";
    private static final String USER_LOGIN_ID = "userLoginId";
    //保存一些基本设置信息的标签
    private static final String GAP_TO_EDGE = "gapToEdge";
    private static final String TIME_TO_INCREASE_LISTEN_COUNTS = "timeToIncreaseListenCounts";
    private static final String LENGTH_OF_USER_NAME = "lengthOfUserName";
    private static final String ALPHA_OF_PICTURE_MAIN_COLOR = "alphaOfPictureMainColor";
    private static final String LYRIC_CHINESE = "lyricChinese";
    private static final String BACK_TO_TOP_BUTTON_APPEAR = "backToTopButtonAppear";
    private static final String LENGTH_OF_MENU_NAME = "lengthOfMenuName";
    private static final String LEAST_MUSIC_COUNTS_USE_LOCATION = "leastMusicCountsUseLocation";

    private static DataLoadManager sInstance;
    private static final SharedPreferences sPreferences;
    private static SharedPreferences sPreferencesUser;
    private static final String DEFAULT_PREFERENCE_NAME = "com.example.musicplayer";
    private static final String USER_PREFERENCE_NAME = "preference_user_";
    private static int CURRENT_PREFERENCE_USER_ID = 0;

    static {
        sPreferences = MusicPlayerApplication.getInstance().getSharedPreferences(DEFAULT_PREFERENCE_NAME, Context.MODE_PRIVATE);
    }

    private DataLoadManager() {
        String preferenceName = USER_PREFERENCE_NAME + User.getInstance().getUserId();
        sPreferencesUser = MusicPlayerApplication.getInstance().getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
    }

    public static DataLoadManager getInstance() {
        User user = User.getInstance();
        if (user == null) {
            return null;
        }
        if (sInstance != null && CURRENT_PREFERENCE_USER_ID != user.getUserId()) {
            sInstance = null;
        }
        if (sInstance == null) {
            CURRENT_PREFERENCE_USER_ID = user.getUserId();
            sInstance = new DataLoadManager();
        }
        return sInstance;
    }

    //写入音乐状态数据信息
    public void writeMusicData(MusicData musicData) {
        if (musicData != null) {
            SharedPreferences.Editor editor = sPreferencesUser.edit();
            editor.putString(MUSIC_LIST_TYPE, musicData.getMusicListType());
            editor.putString(MUSIC_PLAY_MODE, musicData.getPlayMode());
            editor.putString(MUSIC_MENU_NAME, musicData.getMusicMenuName());
            editor.putInt(CURRENT_MUSIC_ID, musicData.getMusicId());
            editor.putInt(CURRENT_MUSIC_TIME, musicData.getCurrentTime());
            List<Integer> list = musicData.getPlayList();
            editor.putInt(CURRENT_MUSIC_COUNTS, list.size());
            for (int i = 0; i < list.size(); i++) {
                String key = CURRENT_MUSIC_LIST + (i + 1);
                editor.putInt(key, list.get(i));
            }
            editor.apply();
        }
    }

    //读取音乐数据信息
    public MusicData readMusicData() {
        String musicListType = sPreferencesUser.getString(MUSIC_LIST_TYPE, MusicListType.TYPE_LOCAL.toString());
        String musicPlayMode = sPreferencesUser.getString(MUSIC_PLAY_MODE, MusicPlayMode.RANDOM.toString());
        String musicMenuName = sPreferencesUser.getString(MUSIC_MENU_NAME, " ");
        int musicCounts = sPreferencesUser.getInt(CURRENT_MUSIC_COUNTS, 0);
        int musicId;
        int musicTime;
        List<Integer> musicList = new ArrayList<Integer>();
        if (musicCounts <= 0)
            musicId = musicTime = 0;
        else {
            musicId = sPreferencesUser.getInt(CURRENT_MUSIC_ID, 0);
            musicTime = sPreferencesUser.getInt(CURRENT_MUSIC_TIME, 0);
            for (int i = 1; i <= musicCounts; i++) {
                String key = CURRENT_MUSIC_LIST + i;
                musicList.add(sPreferencesUser.getInt(key, 0));
            }
        }
        return new MusicData(musicListType, musicPlayMode, musicMenuName, musicId, musicTime, musicList);
    }

    //保存基本设置数据
    public void writeBaseData() {
        SharedPreferences.Editor editor = sPreferencesUser.edit();
        editor.putInt(GAP_TO_EDGE, MusicPlayerSettings.getGapToEdge());
        editor.putInt(TIME_TO_INCREASE_LISTEN_COUNTS, MusicPlayerSettings.getTimeToIncreaseListenCounts());
        editor.putInt(LENGTH_OF_USER_NAME, MusicPlayerSettings.getLengthOfUserName());
        editor.putInt(ALPHA_OF_PICTURE_MAIN_COLOR, MusicPlayerSettings.getAlphaOfPictureMainColor());
        editor.putInt(LYRIC_CHINESE, MusicPlayerSettings.getLyricChinese());
        editor.putInt(BACK_TO_TOP_BUTTON_APPEAR, MusicPlayerSettings.getBackToTopButtonAppear());
        editor.putInt(LENGTH_OF_MENU_NAME, MusicPlayerSettings.getLengthOfMenuName());
        editor.putInt(LEAST_MUSIC_COUNTS_USE_LOCATION, MusicPlayerSettings.getLeastMusicCountsUseLocation());
        editor.apply();
    }

    public static void writeLoginState() {
        SharedPreferences.Editor editor = sPreferences.edit();
        boolean userLogin = UserManage.getUserLogin();
        int userLoginId = UserManage.getLastUserId();
        editor.putBoolean(USER_LOGIN, userLogin);
        editor.putInt(USER_LOGIN_ID, userLoginId);
        editor.apply();
    }

    //写入整型数据
    public void writeOneBaseData(String dataTag, int data) {
        if (checkDataTag(dataTag)) {
            SharedPreferences.Editor editor = sPreferencesUser.edit();
            editor.putInt(dataTag, data);
            editor.apply();
        }
    }

    //写入字符串
    public void writeOneBaseData(String dataTag, String data) {
        if (checkDataTag(dataTag)) {
            SharedPreferences.Editor editor = sPreferencesUser.edit();
            editor.putString(dataTag, data);
            editor.apply();
        }
    }

    //写入整型数据
    public void writeOneBaseData(String dataTag, boolean data) {
        if (checkDataTag(dataTag)) {
            SharedPreferences.Editor editor = sPreferencesUser.edit();
            editor.putBoolean(dataTag, data);
            editor.apply();
        }
    }

    public int readOneBaseData(String dataTag, int defaultValue) {
        int data = defaultValue;
        if (checkDataTag(dataTag)) {
            data = sPreferencesUser.getInt(dataTag, defaultValue);
        }
        return data;
    }

    public boolean readOneBaseData(String dataTag, boolean defaultValue) {
        boolean data = defaultValue;
        if (checkDataTag(dataTag)) {
            data = sPreferencesUser.getBoolean(dataTag, defaultValue);
        }
        return data;
    }

    //初始化基本设置信息
    public void readBaseData() {
        MusicPlayerSettings.setGapToEdge(sPreferencesUser.getInt(GAP_TO_EDGE,
                MusicPlayerSettings.getGapToEdge()));
        MusicPlayerSettings.setTimeToIncreaseListenCounts(sPreferencesUser.getInt(TIME_TO_INCREASE_LISTEN_COUNTS,
                MusicPlayerSettings.getTimeToIncreaseListenCounts()));
        MusicPlayerSettings.setLengthOfUserName(sPreferencesUser.getInt(LENGTH_OF_USER_NAME,
                MusicPlayerSettings.getLengthOfUserName()));
        MusicPlayerSettings.setAlphaOfPictureMainColor(sPreferencesUser.getInt(ALPHA_OF_PICTURE_MAIN_COLOR,
                MusicPlayerSettings.getAlphaOfPictureMainColor()));
        MusicPlayerSettings.setLyricChinese(sPreferencesUser.getInt(LYRIC_CHINESE,
                MusicPlayerSettings.getLyricChinese()));
        MusicPlayerSettings.setBackToTopButtonAppear(sPreferencesUser.getInt(BACK_TO_TOP_BUTTON_APPEAR,
                MusicPlayerSettings.getBackToTopButtonAppear()));
        MusicPlayerSettings.setLengthOfMenuName(sPreferencesUser.getInt(LENGTH_OF_MENU_NAME,
                MusicPlayerSettings.getLengthOfMenuName()));
        MusicPlayerSettings.setLeastMusicCountsUseLocation(sPreferencesUser.getInt(LEAST_MUSIC_COUNTS_USE_LOCATION,
                MusicPlayerSettings.getLeastMusicCountsUseLocation()));
        MusicPlayerSettings.initAutoIntoPlayScreen(sPreferencesUser.getBoolean(AUTO_INTO_PLAY_SCREEN,
                false));
        MusicPlayerSettings.initAllowPlayWithOther(sPreferencesUser.getBoolean(ALLOW_PLAY_WITH_OTHER,
                false));
        MusicPlayerSettings.initUseNotificationBar(sPreferencesUser.getBoolean(USE_NOTIFICATION_BAR,
                true));
        MusicPlayerSettings.initDesktopLyric(sPreferencesUser.getBoolean(DESKTOP_LYRIC,
                false));
        MusicPlayerSettings.initDesktopLyricLock(sPreferencesUser.getBoolean(DESKTOP_LYRIC_LOCK,
                false));
        MusicPlayerSettings.initDesktopLyricInApp(sPreferencesUser.getBoolean(DESKTOP_LYRIC_IN_APP,
                false));
        MusicPlayerSettings.initAnimEffect(sPreferencesUser.getBoolean(ANIM_EFFECT,
                true));
        MusicPlayerSettings.initSetPlayScreenBg(sPreferencesUser.getBoolean(PLAY_SCREEN_BACKGROUND,
                false));
        MusicPlayerSettings.initSetMusicPlayListBg(sPreferencesUser.getBoolean(MUSIC_PLAY_LIST_BACKGROUND,
                false));
        MusicPlayerSettings.initDisplayVisualizer(sPreferencesUser.getBoolean(DISPLAY_VISUALIZER,
                false));
        MusicPlayerSettings.initEnableBassBoost(sPreferencesUser.getBoolean(ENABLE_BASS_BOOST,
                false));
        MusicPlayerSettings.initBassBoostStrength(sPreferencesUser.getInt(BASS_BOOST_STRENGTH,
                0));
        MusicPlayerSettings.initEnableVirtual(sPreferencesUser.getBoolean(ENABLE_VIRTUAL,
                false));
        MusicPlayerSettings.initVirtualStrength(sPreferencesUser.getInt(VIRTUAL_STRENGTH,
                0));
        MusicPlayerSettings.initEnableReverb(sPreferencesUser.getBoolean(ENABLE_REVERB,
                false));
        MusicPlayerSettings.initReverbLevel(sPreferencesUser.getInt(REVERB_LEVEL,
                -9000));
        MusicPlayerSettings.initAddToPlayListTail(sPreferencesUser.getBoolean(ADD_TO_PLAY_LIST_TAIL,
                false));
        //init some settings
        readBaseDataAndInit();
    }

    public static void readLoginState() {
        boolean userLogin = sPreferences.getBoolean(USER_LOGIN, false);
        int id = sPreferences.getInt(USER_LOGIN_ID, -1);
        UserManage.setUserLogin(userLogin);
        UserManage.setLastUserId(id);
        if (userLogin) {
            if (id < 0 || !UserManage.initUser(id)) {
                UserManage.setUserLogin(false);
            }
        }
    }

    //检查preference文件中是否包含此标签
    public boolean checkDataTag(String dataTag) {
        switch (dataTag) {
            case TIME_TO_EXIT_ON:
            case TIMING_SET:
            case TIMED_OFF_IMMEDIATE:
            case AUTO_INTO_PLAY_SCREEN:
            case ALLOW_PLAY_WITH_OTHER:
            case USE_NOTIFICATION_BAR:
            case DESKTOP_LYRIC:
            case DESKTOP_LYRIC_LOCK:
            case DESKTOP_LYRIC_IN_APP:
            case ANIM_EFFECT:
            case PLAY_SCREEN_BACKGROUND:
            case MUSIC_PLAY_LIST_BACKGROUND:
            case DISPLAY_VISUALIZER:
            case ENABLE_BASS_BOOST:
            case BASS_BOOST_STRENGTH:
            case ENABLE_VIRTUAL:
            case VIRTUAL_STRENGTH:
            case ENABLE_REVERB:
            case REVERB_LEVEL:
            case ADD_TO_PLAY_LIST_TAIL:
            case LYRIC_TEXT_SIZE:
            case DESKTOP_LYRIC_VIEW_LOC_Y:
            case DESKTOP_LYRIC_SIZE:
            case DESKTOP_LYRIC_COLOR:
            case DESKTOP_LYRIC_BACKGROUND:
            case PLAY_SCREEN_IMAGE:
            case MUSIC_PLAY_LIST_IMAGE:
            case MUSIC_LIST_TYPE:
            case MUSIC_PLAY_MODE:
            case MUSIC_MENU_NAME:
            case CURRENT_MUSIC_ID:
            case CURRENT_MUSIC_TIME:
            case CURRENT_MUSIC_COUNTS:
            case GAP_TO_EDGE:
            case TIME_TO_INCREASE_LISTEN_COUNTS:
            case LENGTH_OF_USER_NAME:
            case ALPHA_OF_PICTURE_MAIN_COLOR:
            case LYRIC_CHINESE:
            case BACK_TO_TOP_BUTTON_APPEAR:
            case LENGTH_OF_MENU_NAME:
            case LEAST_MUSIC_COUNTS_USE_LOCATION:
                return true;
            default:
                return false;
        }
    }

    private void readBaseDataAndInit() {
        SharedPreferences.Editor editor = sPreferencesUser.edit();
        editor.putBoolean(TIME_TO_EXIT_ON, false);
        editor.putInt(TIMING_SET, SettingsItem.TimedOffItem.TIMING_DEFAULT);
        editor.apply();
    }
}